package com.dinggou.shopjb.activitys;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.dinggou.shopjb.BuildConfig;
import com.dinggou.shopjb.R;
import com.dinggou.shopjb.base.BaseActivity;
import com.dinggou.shopjb.constants.Constant;
import com.dinggou.shopjb.utils.DataUtils;
import com.dinggou.shopjb.utils.LogUtil;
import com.dinggou.shopjb.utils.NetCheckUtil;
import com.dinggou.shopjb.utils.RouteUtil;
import com.dinggou.shopjb.utils.ToastUtil;
import com.dinggou.shopjb.utils.Utils;
import com.dinggou.shopjb.view.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class WebViewActivity extends BaseActivity implements View.OnClickListener, TitleBar.TitleBarListener {
    private WebView wv_web;
    private TitleBar tb_title;
    private View ll_inviation_refresh;
    private View btn_refresh;
    private Handler mHandler = new Handler();
    private ProgressBar pb_loading;
    private String mUrl = "";
    private TextView tv_right;
    private ImageView iv_close;

    private boolean isNeedFinish;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();

//        HashMap<String, String> appendMap = new HashMap<>();
//        appendMap.put("app_id", Constant.APP_ID);
//        appendMap.put("client_id", DataUtils.getClientId(mContext));
//        appendMap.put("oaid", DataUtils.getOAID(mContext));
//        appendMap.put("user_id", DataUtils.getUserId(mContext));
//        appendMap.put("uuid", DataUtils.getUUID(mContext));
//        appendMap.put("version", Utils.getVersion(mContext));
//        appendMap.put("key", DataUtils.getToken(mContext));
//        appendMap.put("host_url", (BuildConfig.SERVER_TYPE.equals("prod") ? "https://7041vc1kl745.vicp.fun" : "https://api-mobile.shengniudinggou.com"));

//        mUrl = DataUtils.isLogin(mContext) ? appendParams(bundle.getString("url"), appendMap) : bundle.getString("url");
        mUrl = bundle.getString("url");
        LogUtil.d("dangzt", "链接是" + mUrl);
        initWebView();
    }

    @SuppressLint("SetJavaScriptEnabled")
    public static void init(Context context, WebView webview, boolean fitWindow) {

        WebSettings settings = webview.getSettings();
        // 自适应屏幕大小
        settings.setUseWideViewPort(fitWindow);
        settings.setLoadWithOverviewMode(fitWindow);

        // WebView 可以加载JavaScript
        settings.setJavaScriptEnabled(true);
        //支持js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        //设置编码
        settings.setDefaultTextEncodingName("utf-8");

        // 提高加载WebView的优先级
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        // 放大缩小
        settings.setDomStorageEnabled(fitWindow);

        // WebView 可以使用数据库
        settings.setDatabaseEnabled(true);

        // 应用可以有缓存
        //settings.setAppCacheEnabled(true);
        //settings.setAppCachePath(cachePath);

//        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置可以支持缩放
        settings.setSupportZoom(fitWindow);
        // 设置出现缩放工具
        settings.setBuiltInZoomControls(fitWindow);
        // 为图片添加放大缩小功能
        settings.setUseWideViewPort(fitWindow);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void initWebView() {
        WebSettings webSettings = wv_web.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        wv_web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.d("shouldOverrideUrlLoading==" + url);
                if (url == null) return false;
                try {
                    if (!url.startsWith("http://") && !url.startsWith("https://")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }

                //处理http和https开头的url
                wv_web.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e("art", "onPageFinished");
                String title = view.getTitle();
                if (!TextUtils.isEmpty(title) && !title.contains("http") && !title.contains("https://") && !wv_web.getUrl().contains(title)) {
                    tb_title.setTitle(title);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

        });

        wv_web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, final int newProgress) {
                super.onProgressChanged(view, newProgress);
                pb_loading.setProgress(newProgress);
                if (newProgress == 100) {
                    iv_close.setVisibility(View.VISIBLE);
                    if (!NetCheckUtil.isNetConnected(mContext)) {
                        ll_inviation_refresh.setVisibility(View.VISIBLE);
                        pb_loading.setVisibility(View.GONE);
                        ToastUtil.showToast(mContext, "请检查网络");
                    } else {
                        wv_web.setVisibility(View.VISIBLE);
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                pb_loading.setVisibility(View.GONE);
                            }
                        }, 500);
                    }
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!TextUtils.isEmpty(title) && !title.contains("http") && !title.contains("https://") && !wv_web.getUrl().contains(title)) {
                    tb_title.setTitle(title);
                }
            }
        });

        wv_web.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//                myApplication.dowloadApk(url);
            }
        });

        wv_web.addJavascriptInterface(new Object() {
            @JavascriptInterface
            public void directToTrade() {
                RouteUtil.toMarketActivity(WebViewActivity.this, "");
            }

            @JavascriptInterface
            public void directToTrade(String proCode) {
                RouteUtil.toMarketActivity(WebViewActivity.this, proCode);
            }

            @JavascriptInterface
            public void directToFollowUserInfo(String userId) {
            }

            @JavascriptInterface
            public void directToRecharge() {
                RouteUtil.toRechargeActivity(WebViewActivity.this);
            }

            @JavascriptInterface
            public String getData() {
                LogUtil.d("dangzt", "拼装得参数" + loginParam());
                return loginParam();
            }

            @JavascriptInterface
            public void directToLuck() {
            }

            @JavascriptInterface
            public void directToGuess() {
            }

            @JavascriptInterface
            public void directToWelfare() {
            }

            @JavascriptInterface
            public void directToUser() {
            }

            @JavascriptInterface
            public void directToSns() {
            }

            @JavascriptInterface
            public void directToTasks() {
                RouteUtil.toWelfareActivity(WebViewActivity.this);
            }

            @JavascriptInterface
            public void directByUrl(String url) {
            }

            @JavascriptInterface
            public void directToSavePay(String money, String imageUrl) {
            }

            @JavascriptInterface
            public void directToCopy(String content) {
                Utils.copyToClipBoard(WebViewActivity.this, content);
            }

            @JavascriptInterface
            public void directToBack() {
                onClickBack();
            }

            @JavascriptInterface
            public void directToFinish() {
                WebViewActivity.this.finish();
            }
        }, "jianyi");

//        wv_web.loadUrl(mUrl);

        loadFaqUrl();

        if (mUrl != null && mUrl.contains("sessionId")) {
            tv_right.setText("打不开？");
            tv_right.setOnClickListener(this);
        }
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_web_view;
    }

    @Override
    protected void findViews() {
        wv_web = (WebView) findViewById(R.id.wv_web);
        tb_title = (TitleBar) findViewById(R.id.tb_title);
        ll_inviation_refresh = findViewById(R.id.ll_inviation_refresh);
        btn_refresh = findViewById(R.id.btn_refresh);
        pb_loading = (ProgressBar) findViewById(R.id.pb_loading);
        tv_right = findViewById(R.id.tv_right);
        iv_close = findViewById(R.id.iv_close);
    }

    @Override
    protected void setListeners() {
        btn_refresh.setOnClickListener(this);
        iv_close.setOnClickListener(this);
        tb_title.setTitleBarListener(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (wv_web.canGoBack() && !isNeedFinish) {
                wv_web.goBack();//返回上一页面
                return true;
            } else {
                backActivity();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
//        loadFaqUrl();
        switch (view.getId()) {
            case R.id.tv_right:
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(mUrl));
                startActivity(intent);
                break;
            case R.id.iv_close:
                finish();
                break;
        }
    }

    private void loadFaqUrl() {
//        wv_web.setVisibility(View.GONE);
        ll_inviation_refresh.setVisibility(View.GONE);
        pb_loading.setVisibility(View.GONE);
        if (!NetCheckUtil.isNetConnected(mContext)) {
            ll_inviation_refresh.setVisibility(View.VISIBLE);
            ToastUtil.showToast(mContext, "请检查网络");
        } else {
            pb_loading.setVisibility(View.VISIBLE);
            wv_web.loadUrl(mUrl);
            LogUtil.d("WebViewActivity--" + mUrl);
        }
    }

    @Override
    public void onLeftClick() {

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public boolean onClickBack() {
        if (wv_web.canGoBack() && !isNeedFinish) {
            wv_web.goBack();
            return false;
        }
        return true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isNeedFinish = true;
    }

    /**
     * 拼接URL和参数。
     *
     * @param url    原始URL字符串
     * @param params 字典形式的参数
     * @return 拼接后的完整URL
     */
    private String appendParams(String url, HashMap<String, String> params) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            boolean isFirstParam = !url.contains("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (isFirstParam) {
                    sb.append('?');
                    isFirstParam = false;
                } else {
                    sb.append('&');
                }
                try {
                    sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                            .append('=')
                            .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace(); // Handle the exception according to your needs
                }
            }
        }
        return sb.toString();
    }

    private String loginParam() {
        if (!DataUtils.isLogin(mContext)) return "";
        JSONObject main = new JSONObject();
        try {
            main.put("app_id", Constant.APP_ID);
            main.put("client_id", DataUtils.getClientId(mContext));
            main.put("oaid", DataUtils.getOAID(mContext));
            main.put("user_id", DataUtils.getUserId(mContext));
            main.put("uuid", DataUtils.getUUID(mContext));
            main.put("version", Utils.getVersion(mContext));
            main.put("token", DataUtils.getToken(mContext));
            main.put("host_url", (BuildConfig.SERVER_TYPE.equals("prod") ? "https://api-mobile.shengniudinggou.com" : "https://7041vc1kl745.vicp.fun"));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return main.toString();
    }
}
